package com.kantboot.system.user.service.impl;

import com.kantboot.system.user.dao.repository.entity.SysUserThirdPartyRepository;
import com.kantboot.system.user.dao.repository.vo.SysUserVOOfSelfRepository;
import com.kantboot.system.user.domain.dto.ThirdPartyLoginDTO;
import com.kantboot.system.user.domain.entity.SysUser;
import com.kantboot.system.user.domain.entity.SysUserThirdParty;
import com.kantboot.system.user.domain.vo.LoginVO;
import com.kantboot.system.user.domain.vo.SysUserOfSelfVO;
import com.kantboot.system.user.exception.SystemUserException;
import com.kantboot.system.user.service.ISysLoginService;
import com.kantboot.system.user.service.ISysThirdPartyService;
import com.kantboot.system.user.service.ISysTokenService;
import com.kantboot.system.user.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class SysThirdPartyServiceImpl implements ISysThirdPartyService {

    @Resource
    private SysUserThirdPartyRepository thirdPartyRepository;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysTokenService tokenService;

    @Resource
    private ISysLoginService loginService;

    @Resource
    private SysUserVOOfSelfRepository sysUserVOOfSelfShowRepository;

    private SysUserOfSelfVO getById(Long userId){
        return sysUserVOOfSelfShowRepository.findById(userId)
                .orElseThrow(() ->
                        // 一般不会出现这种情况，因为前面已经判断过用户名是否存在，如果不存在，就会抛出异常
                        // 提示用户不存在
                        SystemUserException.USER_NOT_EXIST
                );
    }

    @Override
    public LoginVO login(ThirdPartyLoginDTO dto) {
        SysUserThirdParty sysUserThirdParty = thirdPartyRepository.find(dto);
        if(sysUserThirdParty == null){
            SysUser save = userService.createNewUser(dto.getUser());
            sysUserThirdParty = new SysUserThirdParty()
                    .setUserId(save.getId())
                    .setThirdPartyCode(dto.getThirdPartyCode())
                    .setKey(dto.getKey())
                    .setValue(dto.getValue());
            thirdPartyRepository.save(sysUserThirdParty);
        }
        return new LoginVO()
                .setToken(tokenService.generateToken(sysUserThirdParty.getUserId()))
                .setUserInfo(getById(sysUserThirdParty.getUserId()));
    }

    @Override
    public SysUserThirdParty get(ThirdPartyLoginDTO dto) {
        return thirdPartyRepository.find(dto);
    }
}
